package org.example.backend.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.backend.dto.OpeningHoursDTO;
import org.example.backend.dto.Response;
import org.example.backend.entity.OpeningHours;
import org.example.backend.service.OpeningHoursService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "开放时间", description = "园区开放时间管理相关接口")
@RestController
@RequestMapping("/opening-hours")
@RequiredArgsConstructor
public class OpeningHoursController {

    private final OpeningHoursService openingHoursService;

    @Operation(summary = "创建开放时间")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Response<OpeningHours> createOpeningHours(@Valid @RequestBody OpeningHoursDTO openingHoursDTO) {
        return Response.success(openingHoursService.createOpeningHours(openingHoursDTO));
    }

    @Operation(summary = "更新开放时间")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Response<OpeningHours> updateOpeningHours(
            @PathVariable Long id, 
            @Valid @RequestBody OpeningHoursDTO openingHoursDTO) {
        return Response.success(openingHoursService.updateOpeningHours(id, openingHoursDTO));
    }

    @Operation(summary = "删除开放时间")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Response<Void> deleteOpeningHours(@PathVariable Long id) {
        openingHoursService.deleteOpeningHours(id);
        return Response.success();
    }

    @Operation(summary = "获取开放时间详情")
    @GetMapping("/{id}")
    public Response<OpeningHours> getOpeningHours(@PathVariable Long id) {
        return Response.success(openingHoursService.getOpeningHours(id));
    }

    @Operation(summary = "获取所有开放时间")
    @GetMapping
    public Response<List<OpeningHours>> getAllOpeningHours() {
        return Response.success(openingHoursService.getAllOpeningHours());
    }

    @Operation(summary = "获取指定日期的开放时间")
    @GetMapping("/day")
    public Response<OpeningHours> getOpeningHoursByDay(@RequestParam DayOfWeek dayOfWeek) {
        return Response.success(openingHoursService.getOpeningHoursByDay(dayOfWeek));
    }

    @Operation(summary = "检查指定时间是否开放")
    @GetMapping("/check")
    public Response<Boolean> isOpenAt(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateTime) {
        return Response.success(openingHoursService.isOpenAt(dateTime));
    }
} 